MultiCast.py

Set Multicast Mode

It shows how to set transmission mode to multicast mode, that is, querying the user to launch the multicast controlling application or the multicast monitoring application, and opening camera and setting multicast mode in the specified access permission by MV_GIGE_SetTransmissionType().

1 # -- coding: utf-8 --
2 
3 import sys
4 import threading
5 import platform
6 import os
7 from ctypes import *
8 
9 # Compatible with different operating systems to load DDL
10 currentsystem = platform.system()
11 if currentsystem == 'Windows':
12  sys.path.append(os.path.join(os.getenv('MVCAM_COMMON_RUNENV'), "Samples", "Python", "MvImport"))
13 else:
14  sys.path.append(os.path.join("..", "..", "MvImport"))
15 from MvCameraControl_class import *
16 
17 # Compatible with input processing of Python 2.X and 3.X
18 if sys.version_info[0] < 3:
19  # Python 2.x
20  input_func = raw_input
21 else:
22  # Python 3.x
23  input_func = input
24 
25 # Decoding Characters
26 def decoding_char(ctypes_char_array):
27  """
28  Safely decode a string from a ctypes character array.
29  Compatible with Python 2.x and 3.x, as well as 32-bit and 64-bit environments.
30  """
31  byte_str = memoryview(ctypes_char_array).tobytes()
32 
33  # Truncate at the first null character
34  null_index = byte_str.find(b'\x00')
35  if null_index != -1:
36  byte_str = byte_str[:null_index]
37 
38  # Attempt to decode using multiple encodings
39  for encoding in ['gbk', 'utf-8', 'latin-1']:
40  try:
41  return byte_str.decode(encoding)
42  except UnicodeDecodeError:
43  continue
44 
45  # If all encodings fail, use a replacement strategy
46  return byte_str.decode('latin-1', errors='replace')
47 
48 
49 
50 g_bExit = False
51 
52 # Customize the thread function
53 def work_thread(cam=0, pData=0, nDataSize=0):
54  stOutFrame = MV_FRAME_OUT()
55  memset(byref(stOutFrame), 0, sizeof(stOutFrame))
56  while True:
57  ret = cam.MV_CC_GetImageBuffer(stOutFrame, 1000)
58  if None != stOutFrame.pBufAddr and 0 == ret:
59  print ("get one frame: Width[%d], Height[%d], nFrameNum[%d]" % (stOutFrame.stFrameInfo.nWidth, stOutFrame.stFrameInfo.nHeight, stOutFrame.stFrameInfo.nFrameNum))
60  cam.MV_CC_FreeImageBuffer(stOutFrame)
61  else:
62  print ("no data[0x%x]" % ret)
63  if g_bExit == True:
64  break
65 
66 if __name__ == "__main__":
67 
68  try:
69  # Initialize SDK resources
70  MvCamera.MV_CC_Initialize()
71 
72  SDKVersion = MvCamera.MV_CC_GetSDKVersion()
73  print ("SDKVersion[0x%x]" % SDKVersion)
74 
75  deviceList = MV_CC_DEVICE_INFO_LIST()
76  tlayerType = MV_GIGE_DEVICE
77 
78  # Enumerate devices
79  ret = MvCamera.MV_CC_EnumDevices(tlayerType, deviceList)
80  if ret != 0:
81  print ("enum devices fail! ret[0x%x]" % ret)
82  sys.exit()
83 
84  if deviceList.nDeviceNum == 0:
85  print ("find no device!")
86  sys.exit()
87 
88  print ("find %d devices!" % deviceList.nDeviceNum)
89 
90  for i in range(0, deviceList.nDeviceNum):
91  mvcc_dev_info = cast(deviceList.pDeviceInfo[i], POINTER(MV_CC_DEVICE_INFO)).contents
92  if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE:
93  print ("\ngige device: [%d]" % i)
94  strModeName = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chModelName)
95  print ("device model name: %s" % strModeName)
96  strSerialNumber = decoding_char(mvcc_dev_info.SpecialInfo.stGigEInfo.chSerialNumber)
97  print("device serial number: %s" % strSerialNumber)
98  nip1 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0xff000000) >> 24)
99  nip2 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x00ff0000) >> 16)
100  nip3 = ((mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x0000ff00) >> 8)
101  nip4 = (mvcc_dev_info.SpecialInfo.stGigEInfo.nCurrentIp & 0x000000ff)
102  print ("current ip: %d.%d.%d.%d\n" % (nip1, nip2, nip3, nip4))
103 
104 
105  nConnectionNum = input_func("please input the number of the device to connect:")
106 
107  if int(nConnectionNum) >= deviceList.nDeviceNum:
108  print ("intput error!")
109  sys.exit()
110 
111  # Create the camera instance
112  cam = MvCamera()
113 
114  # Select a device, and create a handle
115  stDeviceList = cast(deviceList.pDeviceInfo[int(nConnectionNum)], POINTER(MV_CC_DEVICE_INFO)).contents
116 
117  ret = cam.MV_CC_CreateHandle(stDeviceList)
118  if ret != 0:
119  raise Exception ("create handle fail! ret[0x%x]" % ret)
120 
121  # Ask the user to launch the multicast controlling application or the multicast monitoring application
122  #en:Ask the user to launch: the multicast controlling application or the multicast monitoring application.
123  print ("start multicast sample in (c)ontrol or in (m)onitor mode? (c/m)")
124 
125  key = input_func()
126 
127  # Search for the mode used by the user
128  monitor = False
129  if key == 'm' or key == 'M':
130  monitor = True
131  elif key == 'c' or key == 'C':
132  monitor = False
133  else:
134  raise Exception ("intput error!")
135 
136  if monitor:
137  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Monitor, 0)
138  if ret != 0:
139  raise Exception ("open device fail! ret[0x%x]" % ret)
140  else:
141  ret = cam.MV_CC_OpenDevice(MV_ACCESS_Control, 0)
142  if ret != 0:
143  raise Exception ("open device fail! ret[0x%x]" % ret)
144 
145  # Get optimal packet size (only supported by GigE devices)
146  if stDeviceList.nTLayerType == MV_GIGE_DEVICE:
147  nPacketSize = cam.MV_CC_GetOptimalPacketSize()
148  if int(nPacketSize) > 0:
149  ret = cam.MV_CC_SetIntValue("GevSCPSPacketSize",nPacketSize)
150  if ret != 0:
151  print ("Warning: Set Packet Size fail! ret[0x%x]" % ret)
152  else:
153  print ("Warning: Get Packet Size fail! ret[0x%x]" % nPacketSize)
154 
155  # Specify the multicast IP address
156  strIp = "239.0.1.23"
157  device_ip_list = strIp.split('.')
158  dest_ip = (int(device_ip_list[0]) << 24) | (int(device_ip_list[1]) << 16) | (int(device_ip_list[2]) << 8) | int(device_ip_list[3])
159  print ("dest ip: %s" % strIp)
160 
161  # Specify the multicast port
162  stTransmissionType = MV_TRANSMISSION_TYPE()
163  memset(byref(stTransmissionType), 0, sizeof(MV_TRANSMISSION_TYPE))
164 
165  stTransmissionType.enTransmissionType = MV_GIGE_TRANSTYPE_MULTICAST
166  stTransmissionType.nDestIp = dest_ip
167  stTransmissionType.nDestPort = 8787
168 
169  ret = cam.MV_GIGE_SetTransmissionType(stTransmissionType)
170  if MV_OK != ret:
171  raise Exception ("set transmission type fail! ret [0x%x]" % ret)
172 
173  # Start grabbing images
174  ret = cam.MV_CC_StartGrabbing()
175  if ret != 0:
176  raise Exception ("start grabbing fail! ret[0x%x]" % ret)
177 
178  try:
179  hThreadHandle = threading.Thread(target=work_thread, args=(cam, None, None))
180  hThreadHandle.start()
181  except:
182  raise Exception ("error: unable to start thread")
183 
184  print ("press Enter key to stop grabbing.")
185  input_func()
186 
187  g_bExit = True
188  hThreadHandle.join()
189 
190  # Stop grabbing images
191  ret = cam.MV_CC_StopGrabbing()
192  if ret != 0:
193  raise Exception ("stop grabbing fail! ret[0x%x]" % ret)
194 
195  # Turn off the device
196  ret = cam.MV_CC_CloseDevice()
197  if ret != 0:
198  raise Exception ("close deivce fail! ret[0x%x]" % ret)
199 
200  # Destroy the handle
201  cam.MV_CC_DestroyHandle()
202  except Exception as e:
203  print(e)
204  cam.MV_CC_CloseDevice()
205  cam.MV_CC_DestroyHandle()
206  finally:
207  # Release SDK resources
208  MvCamera.MV_CC_Finalize()
209